import axios from "axios"
import { getToken } from "./auth"
import store from "@/store"
import { customHistory } from "./history"
import { logout } from "@/store/actions/user"
// import store from "@/store"
const service = axios.create({
  baseURL: "http://toutiao.itheima.net/v1_0",
  timeout: 5000,
})
service.interceptors.request.use((config) => {
  // const {
  //   user: { token },
  // } = store.getState()
  config.headers["Authorization"] = `Bearer ${getToken()}`
  return config
})
service.interceptors.response.use(
  (response) => {
    // response是最原始的数据
    return response?.data?.data || response
  },
  (error) => {
    if (error.response.status === 401) {
      // console.log("出现401异常")
      // token失效 token要清空  回到登陆页
      store.dispatch(logout()) // 清空token
      // console.log(customHistory.location.pathname)
      customHistory.replace({
        pathname: "/login",
        state: {
          from: customHistory.location.pathname, // 记住当前哪个地址访问失败
        },
      })
    }
    return Promise.reject(error)
  }
)
export default service
